package com.itheima.reggie.web.controller;

import com.itheima.reggie.config.common.R;
import com.itheima.reggie.utils.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件上传下载
 *
 * @Name FileUpDownLoadController
 * @Author BaiXin
 * @Date 2022-11-02 18:38
 */
@RestController
@RequestMapping("/common")
public class FileUpDownLoadController {

    @Value("${reggie.imgPath}")
    private String imgPath;

    /**
     * 图片上传 随机文件名多级路径
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {

        //生成文件名(包含三级路径)
        String fileNameWithPath = FileUtil.getFileNameWithPath();

        //创建文件夹
        FileUtil.makeDirs(fileNameWithPath, imgPath);

        //获取文件后缀
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        String imgName = fileNameWithPath + suffix;
        file.transferTo(new File(imgPath, imgName));
        R r = new R();
        r.setCode(1);
        r.setMsg("上传成功");
        r.setData(imgName);
        return r;
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException{
        // 拼接文件名
        // String fileName = imgPah + name;

        // 读取文件
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(new File(imgPath, name)));
        } catch (FileNotFoundException e) {
            // 文件不存在
            e.printStackTrace();
            return;
        }

        // 设置响应头，告诉浏览器相应的图片
        response.setContentType("image/jpeg");

        // 从响应体获取输出流
        ServletOutputStream os = response.getOutputStream();


        // 边读边写
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = bis.read(bytes)) > 0) {
            os.write(bytes, 0, len);
            os.flush();
        }

        // 关闭流释放资源
        bis.close();
    }
}
